﻿using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using NP.BPMReportPlatform.BPMPlatform;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.Entities.BPM_Business;
using NP.BPMReportPlatform.Utils;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Linq;
using NP.BPMReportPlatform.Reports.POCAP.Dtos;
using Serilog;
using Microsoft.Extensions.Configuration;
using NP.Enterprise.Utils.Http;

namespace NP.BPMReportPlatform.Reports.POCAP
{
    public class POCAPService : BPMReportPlatformAppService, IPOCAPService
    {
        private readonly SqlSugarClient _db;
        private readonly SqlSugarClient _dbPlatform;
        private readonly IBPMUtilsAppService _bPMUtilsApp;
        private readonly IBPMPlatformAppService _iBPMPlatformApp;
        private readonly ILogger _logger;
        private readonly IConfiguration _configuration;
        private readonly INPRestHttpHelper _nPRestHttp;
        public POCAPService(ISqlSugarAppService sqlSugarAppService, IBPMUtilsAppService bPMUtilsApp
            , IBPMPlatformAppService iBPMPlatformApp, ILogger logger, IConfiguration configuration
            , INPRestHttpHelper nPRestHttp)
        {
            _db = sqlSugarAppService.GetBusinessInstance();
            _dbPlatform = sqlSugarAppService.GetPlatformInstance();
            _bPMUtilsApp = bPMUtilsApp;
            _iBPMPlatformApp = iBPMPlatformApp;
            _logger = logger;
            _configuration = configuration;
            _nPRestHttp = nPRestHttp;
        }

        /// <summary>
        /// 单据解锁
        /// </summary>
        /// <returns></returns>
        public async Task<string> PWSCodeUnlock(string instanceNumber)
        {
            var pwsCodes = await _db.Queryable<POCAPHDetail>()
                .Where(x => x.InstanceNumber == instanceNumber).Select(x => x.PWSCode).ToListAsync();

            if (!pwsCodes.Any())
            {
                throw new Exception("没找到相关PWS单号");
            }

            var res = new List<string>();
            try
            {
                var headers = new Dictionary<string, string>
                {
                    { "Content-Type", "application/json" },
                    { "requestId", Guid.NewGuid().ToString() },
                    { "trackId", Guid.NewGuid().ToString() },
                    { "sourceSystem", "BPMNEW" },
                    { "serviceName", "S_XXX_ERPPP_ZwsChangePwsApp_S" }
                };
                var resbItems = new List<dynamic>();
                pwsCodes = pwsCodes.Distinct().ToList();
                foreach (var pwsCode in pwsCodes)
                {
                    var newItem = new
                    {
                        AUFNR = pwsCode.Trim(),
                        POSNR = "",
                        MATNR = "",
                        EINHEIT = "",
                        MENGE = "",
                        NOMNG = "",
                        ALPGR = "",
                        EWAHR = "",
                        POSTP = "",
                        VORNR = "",
                        ZTEXT1 = "X",
                        ZTEXT2 = "",
                        ZTEXT3 = "",
                        ZTEXT4 = "",
                        ZTEXT5 = "",
                        ZTEXT6 = "",
                        ZTEXT7 = "",
                        ZTEXT8 = "",
                        ZTEXT9 = "",
                        ZTEXT10 = ""
                    };
                    resbItems.Add(newItem);
                }
                // 拼接dynamic模型
                var sendData = new
                {
                    Root = new ESB_SAPRoot(),
                    ZPP_CHANGE_PWS_APP = new
                    {
                        IT_RESB = new
                        {
                            item = resbItems
                        }
                    }
                };

                var reqContent = JsonConvert.SerializeObject(sendData);
                var result = await _nPRestHttp.ESBPostAsync(_configuration["Nippon:ESB:ESBErpppApi"], reqContent, headers);
                if (result == null)
                {
                    _logger.Error($"ZwsChangePwsApp 服务请求失败,{reqContent}，返回为null");
                    res.Add("PWS单号标记失败");
                }
                var returnDto = JsonConvert.DeserializeObject<JObject>(result);
                if (!returnDto.ContainsKey("ZPP_CHANGE_PWS_APPResponse"))
                {
                    _logger.Error($"ZwsChangePwsApp 服务请求失败,{reqContent}，ZPP_CHANGE_PWS_APPResponse 返回数据缺失");
                    res.Add("PWS单号标记失败");
                }
                var responseDto = returnDto.Value<JObject>("ZPP_CHANGE_PWS_APPResponse");
                if (!responseDto.ContainsKey("E_STATUS"))
                {
                    _logger.Error($"ZwsChangePwsApp 服务请求失败,{reqContent}，E_STATUS 返回数据缺失");
                    res.Add("PWS单号标记失败");
                }
                var status = responseDto.Value<string>("E_STATUS");
                if (status == "0")
                {
                    return "解锁成功";
                }
                else
                {
                    if (!responseDto.ContainsKey("E_MESSAGE"))
                    {
                        _logger.Error($"ZwsChangePwsApp 服务请求失败,{reqContent}，E_MESSAGE 返回数据缺失");
                        res.Add("PWS单号标记失败");
                    }
                    else
                    {
                        var message = responseDto.Value<string>("E_MESSAGE");
                        if (string.IsNullOrEmpty(message))
                        {
                            _logger.Error($"ZwsChangePwsApp 服务请求失败,{reqContent}，E_MESSAGE 数据为空");
                            res.Add("PWS单号标记失败");
                        }
                        res.Add(message);
                    }
                }
            }
            catch (Exception e)
            {
                _logger.Error("标记接口出错，ZwsChangePwsApp：" + e.Message);
                res.Add(e.Message);
            }

            throw new Exception(res.JoinAsString("；"));
        }
    }
}
